const mongoose = require('mongoose');

/**
 * 用户活动日志模型
 * 用于记录系统中的用户操作，支持审计跟踪和安全监控
 */
const userActivityLogSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true
  },
  userType: {
    type: String,
    enum: ['user', 'admin'],
    required: true
  },
  actionType: {
    type: String,
    required: true,
    index: true
  },
  module: {
    type: String,
    required: true,
    index: true
  },
  details: {
    object: {
      type: mongoose.Schema.Types.ObjectId,
      index: true
    },
    description: {
      type: String,
      required: true
    },
    oldValue: mongoose.Schema.Types.Mixed,
    newValue: mongoose.Schema.Types.Mixed
  },
  ipAddress: {
    type: String
  },
  userAgent: {
    type: String
  },
  deviceInfo: {
    platform: String,
    model: String,
    system: String
  },
  status: {
    type: String,
    enum: ['success', 'failed'],
    default: 'success',
    required: true
  },
  errorMessage: {
    type: String
  },
  createdAt: {
    type: Date,
    default: Date.now,
    index: true
  }
});

// 创建复合索引以支持高效查询
userActivityLogSchema.index({ userId: 1, module: 1, actionType: 1 });
userActivityLogSchema.index({ module: 1, 'details.object': 1 });
userActivityLogSchema.index({ createdAt: -1 });

/**
 * @typedef UserActivityLog
 */
const UserActivityLog = mongoose.model('UserActivityLog', userActivityLogSchema);

module.exports = UserActivityLog; 